import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import { PAGES_CONFIG } from '../config/pages'
import { BasicLayout } from '../layouts'
import { store } from '../store'
import { getAccessToken } from '../utils/common'
import AsyncRoutes from './routes'

const BasicRoutes: Array<RouteRecordRaw> = [
    {
        path: '/',
        component: BasicLayout,
        redirect: '/home',
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('/@/views/home/index.vue'),
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('/@/views/profile/login/index.vue')
    },
]

/**
 * redirect 路由
 */
const redirectRoute: RouteRecordRaw = {
    path: '/redirect',
    name: 'redirectMain',
    component: BasicLayout,
    children: [
        {
            path: '/redirect/:path(.*)',
            name: 'redirectPath',
            component: () => import('/@/views/profile/redirect/index.vue')
        }
    ]
}

/**
 * 404 匹配路由
 */
const notFundRoute: RouteRecordRaw = {
    path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('/@/views/profile/error/not-found.vue')
}

const routes = BasicRoutes.concat(AsyncRoutes)
routes.push(redirectRoute)

//后续在做了路由授权的时候在追加到别的地方

routes.push(notFundRoute)

export function createWebRouter() {
    return createRouter({
        //在码云上直接部署 history路由会有问题 二级目录spa文件的支持可能还不够
        history: createWebHistory(),
        routes,
    })
}
const router = createWebRouter()

router.beforeEach(async (to, from, next) => {

    if (to.fullPath !== "/login") {
        localStorage.setItem("preRoute", to.fullPath)
    }
    NProgress.inc()
    const accessToken = getAccessToken()
    //如果有token
    if (accessToken) {
        if (to.path === PAGES_CONFIG.LOGIN_URL) {
            // 如果已经登录了 则到首页
            next({ path: '/' })
        } else {
            const hasUserId = store.state.user.userId
            let index = store.state.user.routeMappingMap.get(to.path)
            store.commit("user/SET_FIRST_MENU_INDEX", index)
            if (hasUserId) {
                next()
            } else {
                try {
                    //支持动态路由
                    await store.dispatch('user/getInfo')
                    next({
                        ...to,
                        replace: true
                    })
                } catch (error) {
                    // 删除token 并且跳转到登录页面
                    //await store.dispatch('user/clearToken')
                    next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } })
                }
            }
        }
    } else {
        if (to.path === PAGES_CONFIG.LOGIN_URL) {
            next()
        } else {
            next({ path: PAGES_CONFIG.LOGIN_URL, query: { redirect: to.path } })
        }

    }
})

router.afterEach(() => {
    // 在即将进入新的页面组件前，关闭掉进度条
    NProgress.done()
})

export default router
